package com.cskaoyan.demo1.servlet;

import com.cskaoyan.demo1.util.JsonUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description：
 * @Author：BLUEBLANK
 * @Date：2024/4/9 19:48
 */


public class CommonServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            common(req, resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            common(req, resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void common(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 处理字符集
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        // 利用uri获取请求方法名，并调用相应的方法
        String uri = req.getRequestURI();
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        Object result = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class).invoke(this, req, resp);

        // 对result进行处理 不为null时，将其转换为json字符串返回
        if (result != null) {
            resp.getWriter().println(JsonUtil.write(result));
        }


    }
}
